package com.etc.emsys.dao;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 1.私有化构造函数------------外接无法实例化对象
 * 2.方法使用static
 */
public class JDBCutil {

    private JDBCutil() {

    }

    private static String dirverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        //让程序在类加载的时候执行
        Properties properties = new Properties();
        try {
            properties.load(JDBCutil.class.getClassLoader().getResourceAsStream("db.properties"));
            //给成员属性赋值
            dirverClass = properties.getProperty("dirverClass");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //加载驱动
            Class.forName(dirverClass);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //封装获取连接对象的方法
    public static Connection getConnection() {
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            if (conn != null) {
                return conn;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 封装一个关闭资源的方法
     */

    public static void closeAll(Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
        //判断对象是否为null
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
